<template>
  <el-cascader
    v-bind="$attrs"
    popper-class="v-cascader-hide-radio"
    :props="props"
    :options="options"
    :loading="loading"
    :clearable="clearable"
    :value="value"
    @change="handleCascaderChange"
    filterable
  >
    <div slot-scope="{ node, data }" @click="handleItemChange(node, data)">
      <span>{{ data.agency_name }}</span>
    </div>
  </el-cascader>
</template>

<script>
import { cascaderParse } from '@vimi/utils-tool'
export default {
  components: {},
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    clearable: { type: Boolean, default: true },
    placeholder: { type: String, default: '请选择部门' },
    bankType: { type: String, default: '' },
    value: { type: String },
  },
  data() {
    return {
      options: [],
      select: '',
      selectedLabel: [],
      props: {
        value: 'agency_code',
        label: 'agency_name',
        children: 'children',
        checkStrictly: true,
      },
      parentCode: [],
      hasInit: false,
      loading: false,
      selectData: [],
    }
  },
  watch: {
    value(val) {
      if (val !== this.select) {
        this.init(val)
      }
    },
  },
  created() {
    this.getData()
  },
  mounted() {},
  computed: {},
  methods: {
    async init() {
      this.select = this.value
    },
    async handleItemChange(node, _data) {
      this.select = node.value
      this.$emit('change', node.value, node.label)
      this.$emit('select', node.value, node.label)
    },
    handleCascaderChange(val) {
      const value = (val && val[val.length - 1]) || ''
      const select = this.selectData.find(item => item.agency_code === value) || {}
      this.select = select.agency_code
      this.$emit('change', select.agency_code, select.agency_name)
      this.$emit('select', select.agency_code, select.agency_name)
    },
    async getData() {
      this.options = []
      this.loading = true
      this.$api
        .getData('credit', 'credit_agency_info', {
          'agency_type.eq': '1',
          'agency_type_sub.eq': this.bankType,
        })
        .then(res => {
          this.selectData = (res.data || []).filter(it => !!it.agency_code)
          this.options = cascaderParse({
            data: this.selectData,
            key: 'agency_code',
            parentKey: 'parent_code',
            checkParent: true,
          })
          this.select = this.value
        })
        .finally(() => {
          this.loading = false
        })
    },
    cleared() {
      this.select = []
    },
  },
}
</script>

<style scoped></style>
